package com.sgu6.sgu6_machine.ui.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;

import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;

import com.sgu6.netty.utils.NettyHelper;
import com.sgu6.sgu6_machine.R;
import com.sgu6.sgu6_machine.config.MachineConfig;
import com.sgu6.sgu6_machine.container.MachineContainer;
import com.sgu6.sgu6_machine.event.ProgressEvent;
import com.sgu6.sgu6_machine.service.UpdateAppS;
import com.sgu6.sgu6_machine.ui.MainA;
import com.sgu6.sgu6_machine.ui.views.CircleProgressView;
import com.sgu6.sgu6_machine.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class UpdateDialogF extends DialogFragment {

    protected String TAG = UpdateDialogF.class.getSimpleName();
    @BindView(R.id.tvUpdateTime)
    TextView tvUpdateTime;
    @BindView(R.id.cpv)
    CircleProgressView cpv;

    private Unbinder unbinder;

    private CountDownTimer timer;

    private String apkUrl;
    private Context mContext;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        View v = inflater.inflate(R.layout.dialog_fragment_update, container, false);
        unbinder = ButterKnife.bind(this, v);
        mContext = getActivity();
        Bundle bundle = getArguments();
        if (bundle != null) {
            apkUrl = bundle.getString("apkUrl");
        }

        initUI();

        return v;
    }

    private void initUI() {
        timer = new CountDownTimer(10000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                int second = (int) (millisUntilFinished / 1000);
                tvUpdateTime.setText(second + "s");
            }

            @Override
            public void onFinish() {
                tvUpdateTime.setVisibility(View.GONE);
                timer.cancel();
                cpv.setVisibility(View.VISIBLE);
                cpv.startProgress();

                updateApp();

            }
        }.start();
    }


    @Override
    public void onStart() {
        super.onStart();

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }


        Dialog dialog = getDialog();
        if (dialog != null) {
            DisplayMetrics dm = new DisplayMetrics();
            ((MainA) mContext).getWindowManager().getDefaultDisplay().getMetrics(dm);
            dialog.getWindow().setLayout((int) (dm.widthPixels * 0.4), ViewGroup.LayoutParams.WRAP_CONTENT);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    /**
     * 更新应用
     */
    public void updateApp() {
        //版本更新
        Intent intent = new Intent(getActivity(), UpdateAppS.class);
        intent.putExtra("downloadUrl", apkUrl);
        Log.i(TAG, "onFinish: " + apkUrl);
        mContext.startService(intent);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateProgress(ProgressEvent event) {
        if (event.isDownloading) {
            cpv.setProgress(event.progress);
            NettyHelper.postMsgWithCommandResp(MachineContainer.machineConfigDto.machineNo, "[" + MachineContainer.machineConfigDto.machineNo + "]更新新版本（" + MachineContainer.machineConfigDto.appVersion + "）,进度 " + event.progress);
            if (event.progress == 100) {
                NettyHelper.postMsgWithCommandResp(MachineContainer.machineConfigDto.machineNo, "[" + MachineContainer.machineConfigDto.machineNo + "]更新成功");
            }
        } else {
            ToastUtil.show(getActivity(), "更新失败");
            NettyHelper.postMsgWithCommandResp(MachineContainer.machineConfigDto.machineNo, "[" + MachineContainer.machineConfigDto.machineNo + "]更新失败");
            updateApp();
        }
    }

}
